﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.vCardGE
{
    /// <summary>CCPSIP_054：群組名片交換 - 發起新交換 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// GEName = 群組名片交換名稱。（顯示給 User 參考用）
    /// latitude = 發起人的緯度。(-90 ~ 90)
    /// longitude = 發起人的經度。(-180 ~ 180)
    /// hAccuracy = 發起人的位置誤差半徑，單位為公尺(meter)。
    /// 上傳檔案 = vCard 檔案(.vcf)。

    public class _new : IHttpHandler
    {
        private string kVCardRootDir = ChrisKit.RootDir + "CCPSIP\\vCard";//ios.ccp
        // iCloud: Limits for Contacts
        // http://support.apple.com/kb/HT4489
        private const int kFileSizeLimit = 2 * 1048576;//2MB


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string GEName = req.Form["GEName"];//群組名片交換名稱(顯示用)
                decimal latitude = -1; //緯度
                decimal longitude = -1;//經度
                int hAccuracy = -1;//誤差半徑(meter)
                LocationInfo location = null;

                try
                {
                    latitude = Math.Round(Convert.ToDecimal(req.Form["latitude"]), 6);
                    longitude = Math.Round(Convert.ToDecimal(req.Form["longitude"]), 6);
                    hAccuracy = Convert.ToInt32(Convert.ToDecimal(req.Form["hAccuracy"]));
                    location = new LocationInfo(reqTime, latitude, longitude, hAccuracy);

                    GEName = GEName.Trim();
                    if (GEName.Length < 2)
                        throw new Exception();
                }
                catch
                {
                    throw new Exception("Error_01: Parameter Error");//參數錯誤
                }

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_02: Cannot identify this device");//無法識別此裝置
                }


                //【02】取得上傳的檔案
                //
                if (req.Files.Count < 1 || req.Files[0].ContentLength < 64)
                {
                    throw new Exception("Error_03: No upload file");//沒有上傳檔案
                }
                else if (req.Files[0].ContentLength > kFileSizeLimit)
                {
                    throw new Exception("Error_03: File size exceeds limit");//檔案大小超過上限
                }


                //【03】儲存 vCard 檔案
                //
                string vcfDir = string.Format(@"{0}\{1}", kVCardRootDir, userInfo.SIP_Num);
                if (!Directory.Exists(vcfDir))
                {
                    Directory.CreateDirectory(vcfDir);
                }
                string vcfPath = string.Format(@"{0}\{1}_{2:yyyyMMdd_HHmmss}.vcf", vcfDir, userInfo.SIP_Num, reqTime);
                if (!File.Exists(vcfPath))
                {
                    req.Files[0].SaveAs(vcfPath);
                }


                //【04】儲存群組名片交換資訊
                //
                string ClientKey = OracleKitVCardGE.NewVCardGE(reqTime, userInfo.SIP_Num, GEName, location);


                //【99】回傳Key string
                //
                resultStr = ClientKey;
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
